from tools.md_to_pdf.md_to_pdf import MarkdownToPdfTool
from dify_plugin.core.runtime import Session
from dify_plugin.entities.tool import ToolRuntime

# 读取Markdown文件
with open('example.md', 'r', encoding='utf-8') as f:
    md_text = f.read()

# 自定义CSS样式
custom_css = """
<style>
    /* 整体样式 */
    body {
        font-family: "STSong-Light", "Sans-serif";
        line-height: 1.6;
        color: #333;
        margin: 2em;
    }

    /* 标题样式 */
    h1 {
        color: #2c3e50;
        border-bottom: 2px solid #3498db;
        padding-bottom: 0.3em;
    }

    h2 {
        color: #34495e;
        margin-top: 1.5em;
    }

    h3 {
        color: #7f8c8d;
    }

    /* 列表样式 */
    ul, ol {
        padding-left: 2em;
    }

    li {
        margin: 0.5em 0;
    }

    /* 代码块样式 */
    pre {
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 4px;
        padding: 1em;
    }

    /* 表格样式 */
    table {
        border-collapse: collapse;
        width: 100%;
        margin: 1em 0;
    }

    th, td {
        border: 1px solid #dee2e6;
        padding: 0.75em;
        text-align: left;
    }

    th {
        background-color: #f8f9fa;
    }

    /* 强调文本样式 */
    strong {
        color: #e74c3c;
    }

    em {
        color: #27ae60;
    }
</style>
"""

# 创建运行时和会话对象
runtime = ToolRuntime(credentials={}, user_id=None, session_id=None)
session = Session.empty_session()

# 创建工具实例
tool = MarkdownToPdfTool(runtime=runtime, session=session)

# 准备参数
tool_parameters = {
    "md_text": md_text,
    "custom_css": custom_css,
    "output_filename": "example_output.pdf"
}

# 执行转换
output_file_path = "example_output.pdf"
for message in tool._invoke(tool_parameters):
    if message.type.value == "blob":
        # 保存PDF文件
        with open(output_file_path, "wb") as f:
            f.write(message.message.blob)
        print(f"PDF文件已生成: {output_file_path}")
    elif message.type.value == "text":
        print(f"消息: {message.message.text}")
